// 样式路由
const styleUrl = 'components/ChatCard/index.css';

class ChatCard extends HTMLElement {
  constructor() {
    super();

    const defaultProps = {
      direction: 'left',
      uVatarContent: 'U',
      uName: '这是一个昵称',
      uMessageTime: (new Date()).toLocaleString(),
      uMessageContent: '我是一条消息...',
    };
    // 获取自定义属性
    const customProps = getCustomProps(this.attributes) || {};

    // 属性合并
    this.props = { ...defaultProps, ...customProps };
    
    const shadowRoot = this.attachShadow({ mode: 'open' });

    // 生成模板
    shadowRoot.innerHTML = this.template();
    // 添加样式
    const styleEle = document.createElement('style');
    styleEle.textContent = `@import url(${styleUrl})`;
    shadowRoot.appendChild(styleEle);
  }

  // 模板
  template() {
    // 聊天卡片方向(默认左边)
    const directionFlag = this.props.direction === 'right';

    // 头像文字
    const vatarText = this.props.uVatarContent.slice(0, 1).toLocaleUpperCase() || 'U';

    return `
      <div class="u-message">
        ${!directionFlag ?
        `<div class="u-vatar">
          <div class="u-vatar-content">${vatarText}</div>
        </div>` : ''
        }
        <div class=${!directionFlag ? "u-others" : 'r-u-others'}>
          <div class="u-others-top">
            ${!directionFlag ? `<div class="u-name">${this.props.uName}</div>` : ''}
            <div class="u-message-time">${this.props.uMessageTime}</div>
            ${directionFlag ? `<div class="u-name">${this.props.uName}</div>` : ''}
          </div>
          <div class="u-others-bottom">
            <span class="u-message-content">${this.props.uMessageContent}</span>
          </div>
        </div>
        ${directionFlag ?
        `<div class="r-u-vatar">
          <div class="r-u-vatar-content">${vatarText}</div>
        </div>` : ''
        }
      </div>
    `
  }
}

customElements.define('chat-card', ChatCard);
